package com.jackoak.pen.algorithms;

import edu.princeton.cs.algs4.StdOut;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Bag2<Item> implements Iterable<Item> {

    private Node first;  // 链表头
    private int capacity;  //链表容量

    public Bag2(){

    }

    public boolean isEmpty(){
        return first == null;
    }

    public int size(){
        return this.capacity;
    }

    public void add(Item item){
        Node oldFirst = this.first;
        this.first = new Node();
        this.first.item = item;
        this.first.next = oldFirst;

        this.capacity ++;
    }

    @Override
    public Iterator<Item> iterator() {
        return new ListIterator<>(this.first);
    }


    private class ListIterator<Item> implements Iterator<Item>{

        private Node<Item> currentNode;

        public ListIterator(Node<Item> currentNode){
            this.currentNode = currentNode;
        }


        @Override
        public void remove() {
            throw new UnsupportedOperationException("remove");
        }

        @Override
        public boolean hasNext() {
            return currentNode != null;
        }

        @Override
        public Item next() {
            if(!hasNext()){
                throw new NoSuchElementException();
            }else{
                Item item = this.currentNode.item;
                this.currentNode = this.currentNode.next;
                return item;
            }
        }
    }


    private class Node<Item>{
        private Item item;
        private Node next;

        private Node(){

        }
    }

    public static  void main(String[] args)throws Exception{
        com.jackoak.pen.algorithms.Item item1 = new com.jackoak.pen.algorithms.Item(24,"北京育知路");
        com.jackoak.pen.algorithms.Item item2 = new com.jackoak.pen.algorithms.Item(53,"重庆");
        com.jackoak.pen.algorithms.Item item3 = new com.jackoak.pen.algorithms.Item(34,"美国");
        com.jackoak.pen.algorithms.Item item4 = new com.jackoak.pen.algorithms.Item(12,"济南");

        Bag2<com.jackoak.pen.algorithms.Item> bag2 = new Bag2<>();
        bag2.add(item1);
        bag2.add(item2);
        bag2.add(item3);
        bag2.add(item4);

        for(com.jackoak.pen.algorithms.Item itemFor : bag2){
            StdOut.println(itemFor);
        }

    }

}
